package com.mugui.base.client.net.auto;


import com.mugui.base.base.ApplicationContext;
import com.mugui.base.base.Component;
import com.mugui.base.client.net.base.ManagerInterface;
import com.mugui.base.client.net.classutil.DataSave;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;



@Component
public class AutoLoadManager implements ManagerInterface<String, ManagerInterface> {
	private static HashMap<String, ManagerInterface> map = null;

	public void init() {
		clear();
		map = new HashMap<>();
	}

	public Set<Entry<String, ManagerInterface>> entrySet() {
		return map.entrySet();
	}

	private ApplicationContext applicationContext = null;

	@Override
	public boolean init(Object object) {
		Class<?> name = (Class<?>) object;
		init();
		applicationContext = (ApplicationContext) DataSave.context;
		for (Class<?> class_name : DataSave.initClassList(name)) {
			if (class_name.isAnnotationPresent(AutoManager.class)) {
				AutoManager filter = class_name.getAnnotation(AutoManager.class);
				ManagerInterface managerInterface = null;
				try {
					map.put(filter.hashCode() + "",
							managerInterface = (ManagerInterface) applicationContext.getBean(class_name));
					System.out.println(class_name + "初始化");
					managerInterface.invokeFunction("init", name);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return false;
	}

	@Override
	public boolean clear() {
		if (map != null)
			map.clear();
		return true;
	}

	@Override
	public boolean is(String name) {
		if (map == null) {
			throw new NullPointerException("please run init");
		}
		return !map.isEmpty() && map.get(name) != null;
	}

	@Override
	public ManagerInterface del(String name) {
		if (map == null) {
			throw new NullPointerException("please run init");
		}
		return map.remove(name);
	}

	@Override
	public ManagerInterface get(String name) {
		if (map == null) {
			throw new NullPointerException("please run init");
		}
		return map.get(name);
	}

	@Override
	public boolean add(String name, ManagerInterface object) {
		if (map == null) {
			throw new NullPointerException("please run init");
		}
		return true;

	}

	@Override
	public boolean isInit() {
		// TODO Auto-generated method stub
		return false;
	}

}
